<!-- 弹窗 详情 -->
<script lang="tsx" setup>
import FileUpload from "@/components/file-system/file-upload.vue";
import type { FormDescChild } from "@/components/form-desc/form-desc.vue";
import { whManagerBsTbResponsibilitySaveOrUpdateUsingPost } from "@/genapi/wh";
import { useAsync } from "@/hooks/use-async";
import VisionBox from "@/components/vision-box/vision-box.vue";
import * as Cesium from "cesium";
import { useUserStore } from "@/stores/user";

import { injectState } from "../state";

defineOptions({ name: "DetailDialog" });

const userStore = useUserStore();

const { page } = injectState()!;

const dialogRef = shallowRef<InstanceType<GlobalComponents["PromiseDialog"]>>();
const formDescRef = shallowRef<InstanceType<GlobalComponents["FormDesc"]>>();

const type = ref<"write" | "read">();

const beforeClose = async () => {
	if (type.value === "write") {
		await ElMessageBox.confirm("确认关闭？");
	}
};

const trigger = async (_type: "write" | "read" = "read", value = {} as any) => {
	type.value = _type;
	model.value = JSON.parse(JSON.stringify(value)) as any;
	await dialogRef.value?.open();
	if (value.patrolPlanRoute) {
		drawTempEntities(JSON.parse(value.patrolPlanRoute), { color: "#f00c" });
	}
	if (value.patrolActualRoute) {
		drawTempEntities(JSON.parse(value.patrolActualRoute), {
			color: "#ffc100cc",
		});
	}
};

defineExpose({
	trigger,
});

const model = ref<(typeof page.records.value)[0]>({});

const file = computed({
	get() {
		if (model.value.fileId) {
			return [
				{
					id: model.value.fileId,
					name: model.value.fileName,
				},
			];
		}
	},
	set(value: any) {
		model.value.fileId = value?.[0]?.id;
	},
});

const title = computed(() => {
	if (type.value === "write") {
		return model.value.id ? "编辑" : "新增";
	} else {
		return `详情`;
	}
});

const { execute, isLoading } = useAsync(async () => {
	await formDescRef.value?.formRef?.validate();
	await ElMessageBox.confirm("确认提交？", "提示", {
		type: "warning",
	});

	await whManagerBsTbResponsibilitySaveOrUpdateUsingPost({
		data: {
			...model.value,
		},
	});
	ElMessage.success("提交成功");
	page.execute();
	dialogRef.value?.complete();
});

const children: FormDescChild[] = [
	{
		label: "队伍名称",
		prop: "teamName",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.teamName} placeholder="请输入" />
		),
		descItem: () => `${model.value.teamName ?? "-"}`,
	},
	{
		label: "负责片区",
		prop: "gridName",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.gridName} placeholder="请输入" />
		),
		descItem: () => `${model.value.gridName ?? "-"}`,
	},
	{
		label: "队长姓名",
		prop: "teamLeaderName",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.teamLeaderName} placeholder="请输入" />
		),
		descItem: () => `${model.value.teamLeaderName ?? "-"}`,
	},
	{
		label: "联系电话",
		prop: "teamLeaderPhone",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.teamLeaderPhone} placeholder="请输入" />
		),
		descItem: () => `${model.value.teamLeaderPhone ?? "-"}`,
	},
	{
		label: "队伍成员",
		prop: "fileName",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.fileName} placeholder="请输入" />
		),
		descItem: () => `${model.value.fileName ?? "-"}`,
	},
	{
		label: "巡查频率：",
		prop: "fileName",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.fileName} placeholder="请输入" />
		),
		descItem: () =>
			`${model.value.patrolPlanStartTime ?? "-"} - ${model.value.patrolPlanEndTime ?? "-"}`,
	},
	{
		label: "巡查任务：",
		prop: "patrolTask",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.patrolTask} placeholder="请输入" />
		),
		descItem: () => `${model.value.patrolTask ?? "-"}`,
	},
];

interface User {
	file: string;
	description: string;
}
const tableData: User[] = [
	{
		file: "Aleyna Kutzner",
		description: "园区周围草坪有碎片，需及时清理",
	},
	{
		file: "Aleyna Kutzner",
		description: "园区周围草坪有碎片，需及时清理",
	},
];

const drawPoint = (position, config) => {
	let viewer = userStore.viewer;
	let config_ = config ? config : {};
	return viewer.entities.add({
		name: "点几何对象",
		position: position,
		point: {
			color: Cesium.Color.SKYBLUE,
			pixelSize: 10,
			outlineColor: Cesium.Color.YELLOW,
			outlineWidth: 3,
			disableDepthTestDistance: Number.POSITIVE_INFINITY,
			heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
		},
	});
};

const drawPolyline = (positions, config_) => {
	let viewer = userStore.viewer;
	if (positions.length < 1) return;
	let config = config_ ? config_ : {};
	return viewer.entities.add({
		name: "线几何对象",
		polyline: {
			positions: positions,
			width: config.width ? config.width : 5.0,
			material: new Cesium.PolylineGlowMaterialProperty({
				color: config.color
					? new Cesium.Color.fromCssColorString(config.color)
					: Cesium.Color.GOLD,
			}),
			depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
				color: config.color
					? new Cesium.Color.fromCssColorString(config.color)
					: Cesium.Color.GOLD,
			}),
			clampToGround: true,
		},
	});
};

const drawTempEntities = (tempEntities, config) => {
	if (tempEntities.length < 0) {
		return;
	}
	for (let i = 0; i < tempEntities.value.length - 1; i++) {
		drawPolyline([tempEntities.value[i], tempEntities.value[i + 1]], config);
	}
	tempEntities.value.forEach((item) => {
		drawPoint(item, config);
	});
};
</script>

<template>
	<PromiseDialog
		ref="dialogRef"
		:title="title"
		:before-close="beforeClose"
		w="907px!"
	>
		<el-scrollbar h="408px!">
			<FormDesc
				ref="formDescRef"
				m="t-24px x-30px"
				:type="type === 'read' ? 'desc' : 'form'"
				form-class="gap-x-20px"
				:model="model"
				:children="children"
				:column="2"
			/>
			<el-table :data="tableData" style="width: 94%">
				<el-table-column type="index" label="序号" width="65" />
				<el-table-column label="描述">
					<template #default="scope">{{ scope.row.description }}</template>
				</el-table-column>
				<el-table-column property="file" label="媒体文件" width="190" />
			</el-table>
			<div class="visionBoxContainer">
				<div class="legendBox">
					<div class="legendItem">
						预定路线：
						<div
							style="background-color: #f00c; width: 30px; height: 2px"
						></div>
					</div>
					<div class="legendItem">
						实际路线：
						<div
							style="background-color: #ffc100cc; width: 30px; height: 2px"
						></div>
					</div>
				</div>
				<VisionBox />
			</div>
		</el-scrollbar>
		<template v-if="type === 'write'" #footer>
			<el-button @click="dialogRef?.close()">取消</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>确定</el-button
			>
		</template>
	</PromiseDialog>
</template>

<style lang="scss" scoped>
.visionBoxContainer {
	position: relative;
	margin-top: 10px;
	width: 94%;
	height: 400px;
	.legendBox {
		position: absolute;
		bottom: 5px;
		right: 5px;
		display: flex;
		flex-direction: column;
		width: 120px;
		padding: 4px 10px;
		height: 50px;
		z-index: 999;
		background-color: #fff;
		border-radius: 10px;
		.legendItem {
			width: 100%;
			height: 50%;
			display: flex;
			align-items: center;
			font-size: 12px;
		}
	}
}
</style>
